package com.infolab.aims.web;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.infolab.aims.GlobalConstant;
import com.infolab.aims.common.AbstractController;
import com.infolab.aims.common.ParameterDateQueryHelper;
import com.infolab.aims.common.bean.SearchCriteria;
import com.infolab.aims.common.bean.SearchResult;
import com.infolab.aims.common.exception.ResourceNotFoundException;
import com.infolab.aims.domain.SystemCodeValue;
import com.infolab.aims.domain.Vehicle;
import com.infolab.aims.domain.workorder.WorkOrderAdHoc;
import com.infolab.aims.service.intf.SystemCodeService;
import com.infolab.aims.service.intf.VehicleService;
import com.infolab.aims.service.intf.WorkOrderAdHocService;


@Controller
@RequestMapping("/adHoc")
@SessionAttributes(value=WorkOrderAdHocController.SESSION_SEARCH_CRITERIA)
public class WorkOrderAdHocController extends AbstractController {

	public static final String SESSION_SEARCH_CRITERIA ="searchCriteria";
	public static final String CONTEXT_PATH ="/adHoc";
	public static final String JSP_MAIN_FORM="adHocForm";
	public static final String JSP_MAIN_SEARCH="adHocSearch";

	
	@Autowired
	SystemCodeService systemCodeService;
	
	@Autowired
	WorkOrderAdHocService workOrderAdHocService;
	
	@Autowired
	VehicleService vehicleService;
	
	private void populateWorkOrderAdHocForm(Model model)
	{
		SearchCriteria searchCriteria = new SearchCriteria();
		searchCriteria.addSearchCriteria("systemCodeTypeCode", GlobalConstant.SYSTEM_CODE_TYPE_WORK_ORDER_ADHOC);
		List<SystemCodeValue> systemCodeValues = systemCodeService.findSystemCodeCodeValues(searchCriteria);
		model.addAttribute(systemCodeValues);
	}

	@RequestMapping(value="create", method = RequestMethod.GET)
	public String createWorkOrder(Model model) {

		populateWorkOrderAdHocForm(model);
		
		model.addAttribute(new WorkOrderAdHoc());
		return JSP_MAIN_FORM;
	}

	@RequestMapping(value="create",method=RequestMethod.POST)
	public String saveWorkOrderAdHoc(@ModelAttribute WorkOrderAdHoc workOrderAdHoc, BindingResult result,Model model,HttpServletRequest request) {

		populateWorkOrderAdHocForm(model);
		
		if (validateWorkOrderAdHoc(workOrderAdHoc, result)) {	
			return JSP_MAIN_FORM;
		}

		workOrderAdHocService.createWorkOrderAdHoc(workOrderAdHoc);
		
		setSuccessMessage(getMessageResources("success.create","workOrder " ));

		refreshGlobalSection(request);

		return "redirect:"+CONTEXT_PATH+"/update/" + workOrderAdHoc.getWorkOrderAdHocId();


	}

	@RequestMapping(value="update/{id}",method=RequestMethod.POST)
	public String updateWorkOrderAdHoc(@PathVariable Integer id,@ModelAttribute WorkOrderAdHoc workOrderAdHoc, BindingResult result,Model model,HttpServletRequest request) {

		populateWorkOrderAdHocForm(model);
		
		if (validateWorkOrderAdHoc(workOrderAdHoc, result)) {
			return JSP_MAIN_FORM;
		}

		workOrderAdHocService.updateWorkOrderAdHoc(workOrderAdHoc);
		setSuccessMessage(getMessageResources("success.update","workOrder " ));

		refreshGlobalSection(request);

		return "redirect:"+CONTEXT_PATH+"/update/" + workOrderAdHoc.getWorkOrderAdHocId();	

	}

	@RequestMapping(value={"update/{id}","detail/{id}"}, method = RequestMethod.GET)
	public String detailWorkOrder(@PathVariable Integer id,Model model,HttpServletRequest request) {

		WorkOrderAdHoc workOrderAdHocr = workOrderAdHocService.getWorkOrderAdHoc(id);
		if(workOrderAdHocr==null) {
			throw new ResourceNotFoundException("WorkOrder " + id);
		}
		
		populateWorkOrderAdHocForm(model);

		model.addAttribute(workOrderAdHocr);
		return JSP_MAIN_FORM;

	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(GlobalConstant.DATE_TIME_FORMAT_JAVA);
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}


	@ModelAttribute(WorkOrderAdHocController.SESSION_SEARCH_CRITERIA)
	public SearchCriteria getWorkOrderAdHocSearchCriteria()
	{
		return new SearchCriteria();
	}


	@RequestMapping(value="search")
	public String searchWorkOrder(@ModelAttribute(WorkOrderAdHocController.SESSION_SEARCH_CRITERIA) SearchCriteria searchCriteria,@ModelAttribute("currentSearchCriteria") SearchCriteria currentSearchCriteria,Model model) {

		if(currentSearchCriteria.getCurPage()!=null)
			searchCriteria.setCurPage(currentSearchCriteria.getCurPage());
	
		Date dateFrom = null;
		Date dateTo = null;
		
		try{
			if(!checkNullEmpty(searchCriteria.getSearchCriteria("startAppointmentDate"))) {			 
				dateFrom = new SimpleDateFormat(GlobalConstant.DATE_FORMAT_JAVA).parse(searchCriteria.getSearchCriteria("startAppointmentDate").toString());
			}
		}
		catch (ParseException e) {
			searchCriteria.addSearchCriteria("startAppointmentDate", "");
		}
		
		try{
			
			if(!checkNullEmpty(searchCriteria.getSearchCriteria("endAppointmentDate"))) {			  
				dateTo= new SimpleDateFormat(GlobalConstant.DATE_FORMAT_JAVA).parse(searchCriteria.getSearchCriteria("endAppointmentDate").toString());
			}
		}
		catch (ParseException e) {
			searchCriteria.addSearchCriteria("endAppointmentDate", "");
		}

		if(!checkNullEmpty(dateFrom) &&  !checkNullEmpty(dateTo)) {
			searchCriteria.addSearchCriteria("appointmentDate", new ParameterDateQueryHelper("appointmentDate", dateFrom,dateTo));
		}
		
		else if(!checkNullEmpty(dateFrom) &&  checkNullEmpty(dateTo)){
			searchCriteria.addSearchCriteria("appointmentDate", new ParameterDateQueryHelper("appointmentDate", dateFrom, null));
		}		
		else if(checkNullEmpty(dateFrom) &&  !checkNullEmpty(dateTo)){
			searchCriteria.addSearchCriteria("appointmentDate", new ParameterDateQueryHelper("appointmentDate", null, dateTo));
		}	
		
		SearchResult searchResult = workOrderAdHocService.searchWorkOrderAdHoc(searchCriteria);
		model.addAttribute(searchResult);

		return JSP_MAIN_SEARCH;
	}
	
	public boolean checkNullEmpty(Object obj){
		
		boolean flag=true;
		if(obj!=null && !obj.equals("")){
			flag = false;
		}
		return flag;
	
	
	}

	@RequestMapping(value={"delete/{id}"}, method = RequestMethod.GET)
	public String deleteWorkOrder(@PathVariable Integer id,Model model,HttpServletRequest request) {

		workOrderAdHocService.deleteWorkOrderAdHoc(id);

		refreshGlobalSection(request);

		return "redirect:"+CONTEXT_PATH+"/search";
	}


	private boolean validateWorkOrderAdHoc(WorkOrderAdHoc workOrderAdHoc,BindingResult result)
	{
		if(StringUtils.isEmpty(workOrderAdHoc.getVehicleId()))
			workOrderAdHoc.setVehicleId(null);
		else
		{
			Vehicle vehicle = vehicleService.getVehicle(workOrderAdHoc.getVehicleId());
			if(vehicle==null)
				workOrderAdHoc.setVehicleId(null);
			else
				workOrderAdHoc.setVehicleId(vehicle.getVehicleId());
		}
		validator.validate(workOrderAdHoc, result);

		return result.hasErrors();
	}

}
